package com.guanyong.admin.config;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.guanyong.admin.handle.TokenHelper;
import com.guanyong.model.UserBaseModel;
import com.guanyong.services.UserBaseService;
import com.guanyong.utils.Comm.ResultCode;
import com.guanyong.utils.Comm.ResultObject;
import com.guanyong.utils.UniqueID.LoginTokenID;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import static javax.servlet.http.HttpServletResponse.SC_FORBIDDEN;

/**
 * Created by mxk 2017年6月12日 17:05:12
 */
public  class LoginVisitorInterceptor implements HandlerInterceptor {
    @Autowired
    TokenHelper tokenHelper;
    @Autowired
    UserBaseService userBaseService;






    public String[] allowUrls;//还没发现可以直接配置不拦截的资源，所以在代码里面来排除,不需要登录的

    public void setAllowUrls(String[] allowUrls) {
        this.allowUrls = allowUrls;
    }


    @Value("${mortise.usercas.loginUrl}")
    String loginUrl = "";

    public LoginVisitorInterceptor() {

    }



    /**
     * 获取用户对当前路径是否有访问权限
     *
     * @param Uid
     * @param Path
     * @return
     */
    public  Boolean getVisitRight(String Uid, String Path){
        return true;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        String requestUrl = request.getRequestURI().replace(request.getContextPath(), "");
        if (null != allowUrls && allowUrls.length >= 1) {
            for (String url : allowUrls) {
                if (requestUrl.equals(url)) {
                    return true;
                }
            }
        }
        int pass = 0;
        Boolean isajax = request.getHeader("X-Requested-With") == null ? false : true;
        String token = "";
        String uid = "";
        String pwd = "";
            try {
                ResultObject<LoginTokenID> ltID = tokenHelper.getToken(request);
                if(ltID.getCode().equals(ResultCode.OperateOk)){
                    uid = ltID.getResult().getUid();
                    pwd = ltID.getResult().getPwd();
                    token = ltID.getResult().getUniqueObjectID().toString();
                }
            } catch (Exception ex) {

            }
            if (token != null && token != "") {
                int guSign = tokenHelper.exsitToken(uid,token);
                if (guSign==1) {//缓存中存在该用户的sign
                        pass = 1;
                } else if(guSign==0){//缓存中不存在该用户的sign,需要做模拟登录
                    ResultObject<UserBaseModel>  loginResult=userBaseService.loginByPrimekey(uid, pwd);
                    if (loginResult!=null&&loginResult.getCode().equals(ResultCode.LoginSucess)) {

                        pass = 1;
                    }
                }
                //用户处于登录状态，判断是否有对当前路径访问的权限
                if (pass == 1 && getVisitRight(uid, requestUrl)) {
                    pass = 2;
                }
            }

        if (pass == 2) {//验证通过

            return true;
        } else if (pass == 1) { //权限不足
            if (isajax) {
                ResultObject<Object> result = new ResultObject<Object>();
                result.setCode(ResultCode.NoRule);
                response.getWriter().print(new ObjectMapper().writeValueAsString(result));
            } else {
                response.sendError(SC_FORBIDDEN);
            }
            return false;


        } else {//令牌已失效
            tokenHelper.delMyCasToken(request,response);
            if (isajax) {
                ResultObject<Object> result = new ResultObject<Object>();
                result.setCode(ResultCode.LoginFail);
                response.getWriter().print(new ObjectMapper().writeValueAsString(result));
            } else {
                response.sendRedirect(loginUrl);
            }
            return false;
        }

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object o, ModelAndView modelAndView) throws Exception {



    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object o, Exception e) throws Exception {

    }

}
